﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using A2DFramework.XmlService;
using A2DFramework.LogService.Configuration;
using A2DFramework.NetworkHelpers;

namespace A2DFramework.LogService.LogProviders
{
    public class UdpLogger : ILog
    {
        private UdpClient udpServer = new UdpClient();

        public void Log(Exception ex, params string[] additionalInfos)
        {
            ExceptionWrapper wrapper = new ExceptionWrapper(ex);
            if (additionalInfos != null)
                wrapper.AdditionalInfos = additionalInfos.ToList();

            SendUdpMessage(wrapper);
        }

        public void Log(string message, params string[] additionalInfos)
        {
            ExceptionWrapper wrapper = new ExceptionWrapper(new Exception(message));
            if (additionalInfos != null)
                wrapper.AdditionalInfos = additionalInfos.ToList();

            SendUdpMessage(wrapper);
        }


        private void SendUdpMessage(ExceptionWrapper wrapper)
        {
            wrapper.Ip = IPHelper.GetLocalIPv4();
            string xml = SerializeUtils.Serialize2XML<ExceptionWrapper>(wrapper);
            byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(xml);
            udpServer.Send(bytes, bytes.Length, LogConfiguration.UdpServer, LogConfiguration.UdpPort);
        }
    }
}
